<?php

namespace Drupal\scs_refund;

use Drupal\s_commerce_service\Entity\SCommerceService;
use Drupal\s_commerce_service\SCommerceServiceRefundInterface;
use Drupal\shusy_pay_wx\Entity\ShusyPayWx;
use Drupal\shusy_store_order_pay\Entity\ShusyStoreOrderPay;
use Drupal\wx_pay_refund\WxPayRefundController;

class ScsRefundController implements SCommerceServiceRefundInterface {

  function handler(SCommerceService $commerceService) {
    $refund = WxPayRefundController::init();
    $wxPayTransaction = $this->getWxPay($commerceService->order_id);
    $attach = "{$commerceService->id}";
    $refund->refundTransaction('scs_refund', $wxPayTransaction, $commerceService->amount, $commerceService->reason_desc, $attach);
  }

  protected function getWxPay(int $orderId) {
    $es = shusy_store_order_pay_load_multiple(FALSE, [
      'store_order_id' => $orderId,
      'type' => 'wx',
      'status' => 1,
    ]);
    if (!empty($es)) {
      $e = reset($es);
      if ($e instanceof ShusyStoreOrderPay) {
        $wxs = shusy_pay_wx_load_multiple(FALSE, ['store_order_pay_id' => $e->id]);
        if (!empty($wxs)) {
          $wx = reset($wxs);
          if ($wx instanceof ShusyPayWx) {
            return wx_pay_transaction_load($wx->wx_pay_transaction_id);
          }
        }
      }
    }
    throw new \Exception('无法获取支付记录');
  }

}
